package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.IdWorker;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.meily.behavioral.entity.BehavioralData;
import cn.openea.perpartner.meily.behavioral.service.IBehavioralDataService;
import cn.openea.perpartner.meily.thirdparty.WxPaySystemApi;
import cn.openea.perpartner.meily.web.entity.*;
import cn.openea.perpartner.meily.web.entity.dto.MaterialDownloadDTO;
import cn.openea.perpartner.meily.web.entity.vo.ProvideSamplesSubVo;
import cn.openea.perpartner.meily.web.entity.vo.ProvideSamplesVo;
import cn.openea.perpartner.meily.web.mapper.ProvideSamplesMapper;
import cn.openea.perpartner.meily.web.mapper.ProvideSamplesSubMapper;
import cn.openea.perpartner.meily.web.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;

/**
 * @author ysk
 * @email zane_ysk@qq.com
 * @date 2023-03-27 11:37:04
 */
@Service("provideSamplesService")
public class ProvideSamplesServiceImpl extends ServiceImpl<ProvideSamplesMapper, ProvideSamples> implements IProvideSamplesService {

    @Resource
    private ITaskHallService taskHallService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IGoodsBusinessService goodsBusinessService;
    @Autowired
    private ProvideSamplesSubMapper provideSamplesSubMapper;
    @Resource
    private IProvideSamplesSubService provideSamplesSubService;
    @Resource
    private IBehavioralDataService behavioralDataService;
    @Resource
    private WxPaySystemApi wxPaySystemApi;
    @Autowired
    private RedisCache redisCache;
    @Value("${sso.url}")
    private String ssoUrl;

    private IdWorker worker = new IdWorker(1, 1, 1);

    /**
     * 发布样品发放活动
     * 步骤：
     * 1.保存样品发放详情；
     * 2.保存到需求大厅（需求下架）
     * 3.汇集数据
     * 4.保存一条当前商品记录到meily_goods_business表，用于查询
     *
     * @param provideSamples 实例对象
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult publish(@NonNull ProvideSamples provideSamples) {

        // 样品价格不能小于0
        String msg = provideSamples.checkParams();
        if (StringUtils.isNotBlank(msg)) {
            throw new ServiceException(msg);
        }

        /*// 标题增加随机数
        if (StringUtils.isNotBlank(provideSamples.getSubject())) {
            provideSamples.setSubject(provideSamples.getSubject() + "(" + CommonUtils.getPrefix(3) + ")");
        }*/

        // 校验商品
        Goods goods = Optional.ofNullable(goodsService.findById(provideSamples.getGoodsId()))
                .orElseThrow(() -> new ServiceException("商品不存在"));
        if (!"已上架".equals(goods.getStatus())) {
            // 商品未上架
            throw new ServiceException("商品还未上架");
        }
        provideSamples.setGoodsName(goods.getGoodsName());
        provideSamples.setGoodsNo(goods.getGoodsNo());
        provideSamples.setGoodsImages(goods.getGoodsImages());
        provideSamples.setGoodsTag(goods.getGoodsTag());

        if(StrUtil.isBlank(provideSamples.getSpecification())){
            provideSamples.setSpecification(goods.getSpecification());
        }

        provideSamples.setTaskNumber(String.valueOf(worker.nextId()));// 任务单号，全使用数字
        provideSamples.setAllReaders(provideSamples.getInitiatorId());

        if (baseMapper.insert(provideSamples) < 0) {
            return AjaxResult.error("保存样品发放详情出错了！");
        }

        // 默认不公开
        String taskState = "需求下架";
        String taskStatus = "下架";

        // 公开活动
        if("1".equals(provideSamples.getOpen())){
            taskState = "火热报名";
            taskStatus = "上架";
        }

        // 优惠券金额
        String couponLabel = "";
        BigDecimal amount = new BigDecimal(0);
        if (provideSamples.getLevelACouponAmount().compareTo(BigDecimal.ZERO) > 0) {
            amount = provideSamples.getLevelACouponAmount();
        }

        if(provideSamples.getLevelBCouponAmount().compareTo(BigDecimal.ZERO) > 0){
            if(provideSamples.getLevelBCouponAmount().compareTo(amount) > 0){
                amount = provideSamples.getLevelBCouponAmount();
            }
        }

        if(provideSamples.getLevelCCouponAmount().compareTo(BigDecimal.ZERO) > 0){
            if(provideSamples.getLevelCCouponAmount().compareTo(amount) > 0){
                amount = provideSamples.getLevelCCouponAmount();
            }
        }

        if(amount.compareTo(BigDecimal.ZERO) > 0){
            couponLabel = "评价获" + amount + "元优惠券";
        }

        // 2.保存到需求大厅（需求下架）
        TaskHall taskHall = TaskHall.builder()
                .taskNumber(provideSamples.getTaskNumber())
                .taskName(provideSamples.getSubject())
                .taskPrice(provideSamples.getSamplePrice().setScale(2, RoundingMode.HALF_UP).toString())
                .taskType("样品发放")
                .taskState(taskState)
                .taskStatus(taskStatus)
                // .taskKeyword(goods.getGoodsTag())
                .taskKeyword(provideSamples.getLabel())
                .taskUser("")
                .taskAuthor(provideSamples.getInitiatorId())
                .taskCurrentId(provideSamples.getId())
                .taskHistoryId(provideSamples.getId())
                .sceneId(provideSamples.getSceneId())
                .privateId(provideSamples.getSceneAssetsId())
                .taskLabel("样品推广价")
                .taskColor("#40972f")
                .taskUrl("/pages_private_scene2/provide_samples/sign_up?docUnid=" + provideSamples.getId())
                .createUser(provideSamples.getInitiatorId())
                .createUserName(provideSamples.getInitiatorName())
                .imageUrl(goods.getGoodsImages())
                .collectType("market")
                .couponLabel(couponLabel)
                .build();

        if (!taskHallService.insert(taskHall)) {
            return AjaxResult.error("保存到需求大厅出错了！");
        }

        // 3.汇集数据（用于企业动态的展示）
        /* 发起样品推广
        文案：我刚发布了一个新活动，快来跟我一起组队吧。
        图片：活动首图；标题：活动标题；小字：商品/样品规格；
        品牌推广：金额+标签“品牌推广报酬”
        样品推广：金额+标签“样品推广价”*/
        BehavioralData behavioralData = new BehavioralData();
        behavioralData.setTitle("我刚发布了一个新活动，快来跟我一起组队吧。");// 文案
        behavioralData.setSubject(provideSamples.getSubject());// 标题
        behavioralData.setContent(provideSamples.getSpecification());// 内容（商品/样品规格）
        if(StrUtil.isNotBlank(provideSamples.getGoodsImages())){
            behavioralData.setImage(provideSamples.getGoodsImages().split(",")[0]);// 图片
        }
        behavioralData.setPrice(provideSamples.getSamplePrice().toString());
        behavioralData.setLabel("样品推广价");
        behavioralData.setType("0");// 类型。0动态；1工作；2商品；3创作
        behavioralData.setJumpUrl("/pages_private_scene2/provide_samples/sign_up?docUnid=" + provideSamples.getId());// 样品活动报名页面
        behavioralData.setSourceId(provideSamples.getId());// 来源id
        behavioralData.setSourceType("2");// 来源类型。0团购；1测评；2样品；3招聘；4协作；5上架商品；6发布学习
        behavioralData.setStatus("1");// 状态。0停用；1启用
        behavioralData.setEnterpriseNo(goods.getEnterpriseNo());// 企业编号
        behavioralData.setEnterpriseName(goods.getEnterpriseName());// 企业名称
        behavioralData.setCreateTime(DateUtil.now());
        behavioralData.setUpdateTime(DateUtil.now());
        behavioralData.setUserId(provideSamples.getInitiatorId());
        behavioralData.setUserName(provideSamples.getInitiatorName());

        // 获取用户信息
        JSONObject userObj =  getUserInfoById(provideSamples.getInitiatorId());
        if(BeanUtil.isNotEmpty(userObj)){
            behavioralData.setAvatarUrl(userObj.getString("avatar"));
        }

        if (!behavioralDataService.save(behavioralData)){
            return AjaxResult.error("发布样品行为汇集出错了！");
        }

        // 4.保存一条当前商品记录到meily_goods_business表，用于查询
        GoodsBusiness goodsBusiness = new GoodsBusiness();
        BeanUtils.copyProperties(goods, goodsBusiness);
        goodsBusiness.setBusinessId(provideSamples.getId());// 样品发放流程的主键

        if (!goodsBusinessService.save(goodsBusiness)) {
            return AjaxResult.error("保存一条当前商品记录到meily_goods_business表出错了！");
        }

        return AjaxResult.success("发布成功", provideSamples);
    }

    /**
     * 获取样品发放详情
     *
     * @param id
     * @return 实例对象
     */
    @Override
    public AjaxResult queryById(String id) {

        if (StrUtil.isBlank(id)) {
            return AjaxResult.error("获取不到样品发放记录唯一id！");
        }

        ProvideSamples provideSamples = getById(id);
        if (BeanUtil.isEmpty(provideSamples)) {
            return AjaxResult.error("根据文档id(" + id + ")，获取不到样品发放详情！");
        }
        return AjaxResult.success("获取样品发放详情成功！", provideSamples);
    }

    /**
     * 获取样品发放列表-小程序
     *
     * @param vo
     * @return
     */
    @Override
    public List<ProvideSamples> getAllList(ProvideSamplesSubVo vo) {
        LambdaQueryWrapper<ProvideSamples> wrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(vo.getSearchStr())) {
            wrapper.and(wrap -> wrap.like(ProvideSamples::getGoodsNo, vo.getSearchStr())
                    .or().like(ProvideSamples::getId, vo.getSearchStr())
                    .or().like(ProvideSamples::getSubject, vo.getSearchStr())
                    .or().like(ProvideSamples::getInitiatorId, vo.getSearchStr())
                    .or().like(ProvideSamples::getInitiatorName, vo.getSearchStr())
                    .or().like(ProvideSamples::getGoodsId, vo.getSearchStr())
                    .or().like(ProvideSamples::getGoodsNo, vo.getSearchStr())
                    .or().like(ProvideSamples::getGoodsName, vo.getSearchStr()));
        }
        wrapper.orderByDesc(ProvideSamples::getCreateTime);
        return list(wrapper);
    }

    /**
     * 活动作废
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean finish(ProvideSamplesVo vo) {

        if(StrUtil.isBlank(vo.getId())){
            throw new ServiceException("获取不到参数！");
        }

        ProvideSamples provideSamples = getById(vo.getId());
        if(BeanUtil.isEmpty(provideSamples)){
            throw new ServiceException("样品不存在！");
        }

        // 任务状态。0:正常结束(到期自动结束)；1:正在进行中；2:报名结束；3:活动作废(手动结束)
        if("0".equals(provideSamples.getStatus())){
            throw new ServiceException("活动已结束！");
        } else if("3".equals(provideSamples.getStatus())){
            throw new ServiceException("活动已作废，请勿重复操作！");
        }

        /**
         * 第1步 判断是否已存在发货记录
         * 手动作废活动需要增加一个判断条件：如果样品已发货，则不能作废活动。
         */
        LambdaQueryWrapper<ProvideSamplesSub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProvideSamplesSub::getMainId, vo.getId());
        queryWrapper.in(ProvideSamplesSub::getOrderStatus, "已发货", "已完成", "已评价");// 订单状态：待支付、待发货、已发货、已完成、已评价；(默认待发货)
        long count = provideSamplesSubMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new ServiceException("已存在发货记录，不能作废活动！");
        }

        // 2.修改任务状态
        LambdaUpdateWrapper<ProvideSamples> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProvideSamples::getId, vo.getId());
        updateWrapper.set(ProvideSamples::getStatus, "3");
        updateWrapper.set(ProvideSamples::getFinishTime, DateUtil.now());
        if(!update(updateWrapper)){
            throw new ServiceException("修改任务状态出错了！");
        }

        // 3.作废领取记录
        if(!cancellationRecord(provideSamples.getId())){
            throw new ServiceException("作废领取记录出错了！");
        }

        // 4.从需求大厅下架测评任务
        LambdaUpdateWrapper<TaskHall> updateWrapper2 = new LambdaUpdateWrapper<>();
        updateWrapper2.eq(TaskHall::getTaskCurrentId, provideSamples.getId());
        updateWrapper2.set(TaskHall::getTaskState, "需求下架");
        updateWrapper2.set(TaskHall::getTaskStatus, "下架");
        if(!taskHallService.update(updateWrapper2)){
            throw new ServiceException("需求下架出错了！");
        }

        return true;

    }

    /**
     * 作废领取记录
      * @param id
     * @return
     */
    private boolean cancellationRecord(String id){
        // 获取所有领取记录
        LambdaQueryWrapper<ProvideSamplesSub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProvideSamplesSub::getMainId, id);
        queryWrapper.eq(ProvideSamplesSub::getOrderStatus, "待发货");
        queryWrapper.orderByDesc(ProvideSamplesSub::getCreateTime);
        List<ProvideSamplesSub> list = provideSamplesSubService.list(queryWrapper);

        for (ProvideSamplesSub samplesSub : list){
            String refundNo = "";
            // 1.退还报名费用（大于0，才需要退）
            if(new BigDecimal(samplesSub.getPayAmount()).compareTo(BigDecimal.ZERO) > 0){
                refundNo = wxPaySystemApi.samplesRefund(new BigDecimal(samplesSub.getPayAmount()), "已作废", samplesSub);
            }

            // 2. 更新领取记录状态为“已作废”
            LambdaUpdateWrapper<ProvideSamplesSub> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProvideSamplesSub::getId, samplesSub.getId());
            updateWrapper.set(ProvideSamplesSub::getOrderStatus, "已作废");
            if(StrUtil.isNotBlank(refundNo)){
                updateWrapper.set(ProvideSamplesSub::getRefundNo, refundNo);
                updateWrapper.set(ProvideSamplesSub::getRefundTime, DateUtil.now());
                updateWrapper.set(ProvideSamplesSub::getRefundAmount, new BigDecimal(samplesSub.getPayAmount()));
            }
            if(!provideSamplesSubService.update(updateWrapper)){
                throw new ServiceException("更新领取记录状态出错了！");
            }
        }

        return true;
    }

    /**
     * 活动结束报名
     * @param vo
     * @return
     */
    @Override
    public boolean endJoin(ProvideSamplesVo vo) {
        if(StrUtil.isBlank(vo.getId())){
            throw new ServiceException("获取不到参数！");
        }

        ProvideSamples provideSamples = getById(vo.getId());
        if(BeanUtil.isEmpty(provideSamples)){
            throw new ServiceException("样品不存在！");
        }

        // 任务状态。0:正常结束(到期自动结束)；1:正在进行中；2:报名结束；3:活动作废(手动结束)
        if("0".equals(provideSamples.getStatus())){
            throw new ServiceException("活动已结束！");
        } else if("2".equals(provideSamples.getStatus())){
            throw new ServiceException("活动已结束报名，请勿重复操作！");
        } else if("3".equals(provideSamples.getStatus())){
            throw new ServiceException("活动已作废！");
        }

        LambdaUpdateWrapper<ProvideSamples> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProvideSamples::getId, vo.getId());
        updateWrapper.set(ProvideSamples::getStatus, "2");
        return update(updateWrapper);
    }

    /** ********************************* 以下是定时任务  start ****************************************** */

    /**
     * 结束样品任务
     * 每天07:40分执行一次
     * @return
     */
    @Scheduled(cron = "${sample.end_task.cron}")
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void automaticFinish() {

        System.out.println("********************************");
        System.out.println("开始执行定时任务：到达“活动结束时间”一周后结束样品任务（修改样品状态Status = '0'）....");

        List<ProvideSamples> list = baseMapper.getNextEndAWeekTaskList();
        for(ProvideSamples samples : list) {
            // 结束任务
            LambdaUpdateWrapper<ProvideSamples> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProvideSamples::getId, samples.getId());
            updateWrapper.in(ProvideSamples::getStatus, "1", "2");// 任务状态。0:正常结束(到期自动结束)；1:正在进行中；2:报名结束；3:活动作废(手动结束)

            updateWrapper.set(ProvideSamples::getStatus, "0");
            updateWrapper.set(ProvideSamples::getFinishTime, DateUtil.now());
            if(!update(updateWrapper)){
                throw new ServiceException("结束任务出错了，出错id=" + samples.getId());
            }
        }
        System.out.println("**************执行结束！******************");
        System.out.println("********************************");
    }


    /**
     * 样品结束一周后从需求大厅下架
     * 每天07:50分执行一次
     * @return
     */
//    @Scheduled(cron = "${sample.off_shelf.cron}")
//    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void automaticOffShelf(){

        System.out.println("********************************");
        System.out.println("开始执行定时任务：样品结束一周后从需求大厅下架....");

        List<ProvideSamples> list = baseMapper.getEndAWeekTaskList();
        for(ProvideSamples samples : list){

            // 再次判断，已发布时间为准，一个月后的样品活动，才需要下架
            LambdaUpdateWrapper<TaskHall> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TaskHall::getTaskCurrentId, samples.getId());
            updateWrapper.apply(" DATE_FORMAT(date_add(create_time, interval 1 month), '%Y-%m-%d') = DATE_FORMAT(now(), '%Y-%m-%d') ");

            updateWrapper.set(TaskHall::getTaskState, "需求下架");
            updateWrapper.set(TaskHall::getTaskStatus, "下架");
            if(!taskHallService.update(updateWrapper)){
                throw new ServiceException("需求下架出错了，出错id=" + samples.getId());
            }
        }

        System.out.println("**************执行结束！******************");
        System.out.println("********************************");

    }

    /**
     * 样品结束一个月后从需求大厅下架
     * 每天07:50分执行一次
     * @return
     */
    @Scheduled(cron = "${sample.off_shelf.cron}")
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void automaticOffShelf_AMonth(){

        System.out.println("********************************");
        System.out.println("开始执行定时任务：样品结束一个月后从需求大厅下架....");

        List<ProvideSamples> list = baseMapper.getEndAMonthTaskList();
        for(ProvideSamples samples : list){

            // 再次判断，已发布时间为准，一个月后的样品活动，才需要下架
            LambdaUpdateWrapper<TaskHall> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TaskHall::getTaskCurrentId, samples.getId());
            updateWrapper.apply(" DATE_FORMAT(date_add(create_time, interval 1 month), '%Y-%m-%d') = DATE_FORMAT(now(), '%Y-%m-%d') ");

            updateWrapper.set(TaskHall::getTaskState, "需求下架");
            updateWrapper.set(TaskHall::getTaskStatus, "下架");
            if(!taskHallService.update(updateWrapper)){
                throw new ServiceException("需求下架出错了，出错id=" + samples.getId());
            }
        }

        System.out.println("**************执行结束！******************");
        System.out.println("********************************");

    }

    /** ********************************* 以上是定时任务  end ****************************************** */

    /**
     * 获取样品发放列表---分页
     *
     * @param vo
     * @return
     */
    @Override
    public List<ProvideSamples> findListByVo(ProvideSamplesVo vo) {
        LambdaQueryWrapper<ProvideSamples> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(vo.getId())) {
            lambdaQueryWrapper.eq(ProvideSamples::getId, vo.getId());
        }
        if (StringUtils.isNotBlank(vo.getGoodsNo())) {
            lambdaQueryWrapper.eq(ProvideSamples::getGoodsNo, vo.getGoodsNo());
        }
        if (StringUtils.isNotBlank(vo.getGoodsName())) {
            lambdaQueryWrapper.like(ProvideSamples::getGoodsName, vo.getGoodsName());
        }
        lambdaQueryWrapper.orderByDesc(ProvideSamples::getCreateTime);

        List<ProvideSamples> list = baseMapper.selectList(lambdaQueryWrapper);

        for(ProvideSamples provideSamples : list){

            // 获取领取人数
            long receiveQuota = provideSamplesSubMapper.selectCount(new LambdaQueryWrapper<ProvideSamplesSub>()
                    .eq(ProvideSamplesSub::getMainId, provideSamples.getId())
                    .ne(ProvideSamplesSub::getOrderStatus, "已回收")// 不查询“已回收”的记录
                    .ne(ProvideSamplesSub::getOrderStatus, "待支付"));// 不查询“待支付”的记录
            provideSamples.setReceiveQuota((int)receiveQuota);

        }
        return list;
    }


    @Override
    public void editQuota(String id, Integer number) {
        LambdaUpdateWrapper<ProvideSamples> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProvideSamples::getId, id).set(ProvideSamples::getRemainQuota, number);
        this.update(updateWrapper);
    }

    @Override
    public void edit(ProvideSamples provideSamples) {
        baseMapper.updateById(provideSamples);
    }

    @Override
    public MaterialDownloadDTO getMaterialDirectory(String id) {
        ProvideSamples provideSamples = Optional.ofNullable(getById(id))
                .orElseThrow(() -> new ServiceException("样品不存在"));
        MaterialDownloadDTO materialDownloadDTO = MaterialDownloadDTO
                .builder()
                .fileName(provideSamples.getGoodsName())
                .fileType((short)0)
                .build();
        List<MaterialDownloadDTO> samplesMaterialList = provideSamplesSubService.generateTrialMaterialDirectory(id);
        materialDownloadDTO.setChildren(samplesMaterialList);
        return materialDownloadDTO;
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    public JSONObject getUserInfoById(String userId) {

        JSONObject object = new JSONObject();
        // 从缓存获取
        String key = this.getCacheKey(userId);
        if (Boolean.TRUE.equals(redisCache.hasKey(key))) {
            if (redisCache.getCacheObject(key) == null) {
                // 缓存中获取不到，再调接口获取
                JSONObject resObj = getUserCache(userId);
                if (resObj.isEmpty() || !"200".equals(resObj.getString("code"))) {
                    throw new ServiceException("获取用户信息出错了！");
                }
                object = JSONObject.parseObject(resObj.getString("data"));
            } else {
                object = redisCache.getCacheObject(key);
            }
        }
        return object;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return "sys_user:" + configKey;
    }

    /**
     * 用户系统：获取用户信息
     *
     * @return
     */
    public JSONObject getUserCache(String userId) {
        System.out.println("调用用户系统：获取用户信息.................");
        JSONObject obj = new JSONObject();
        HttpResponse resp = HttpRequest.get(ssoUrl + "/user/cache/" + userId)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .execute();
        try {
            obj = JSON.parseObject(resp.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}